/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package program;

import avenue.MyWindowEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import model.DBManager;
import model.Program;
import model.ProgramRate;
import model.Station;
import model.VehicleCategory;

/**
 *
 * @author Aggelos
 */
public class ListProgramForm extends javax.swing.JFrame {

    /**
     * Creates new form ListProgramForm
     */
    public ListProgramForm() {
        em = DBManager.em;
        if ( !em.getTransaction().isActive()){
            em.getTransaction().begin();
        }
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        TelePassPUEntityManager0 = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("TelePassPU").createEntityManager();
        programQuery = java.beans.Beans.isDesignTime() ? null : TelePassPUEntityManager0.createQuery("SELECT p FROM Program p");
        programList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : programQuery.getResultList();
        Pinakas_ = new javax.swing.JScrollPane();
        Pinakas = new javax.swing.JTable();
        Titlos = new javax.swing.JLabel();
        Shma = new javax.swing.JLayeredPane();
        Shma1 = new javax.swing.JLabel();
        Image = new javax.swing.JLabel();
        Shma2 = new javax.swing.JLabel();
        Logotupo = new javax.swing.JLabel();
        Plaisio = new javax.swing.JPanel();
        NeoProgramma__ = new javax.swing.JButton();
        DiaxeirishProgrammatos = new javax.swing.JButton();
        DiagrafhProgrammatos = new javax.swing.JButton();
        Apo8hkeysh = new javax.swing.JButton();
        Plaisio1 = new javax.swing.JPanel();
        Akyro = new javax.swing.JButton();
        DiaxwristikhGrammh = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setEnabled(false);
        setMinimumSize(new java.awt.Dimension(805, 500));
        getContentPane().setLayout(null);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, programList, Pinakas, "");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${description}"));
        columnBinding.setColumnName("Description");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${id}"));
        columnBinding.setColumnName("Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Name");
        columnBinding.setColumnClass(String.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        Pinakas.addContainerListener(new java.awt.event.ContainerAdapter() {
            public void componentAdded(java.awt.event.ContainerEvent evt) {
                Pinakas(evt);
            }
        });
        Pinakas_.setViewportView(Pinakas);

        getContentPane().add(Pinakas_);
        Pinakas_.setBounds(20, 220, 530, 95);

        Titlos.setFont(new java.awt.Font("Lucida Sans", 0, 18)); // NOI18N
        Titlos.setForeground(new java.awt.Color(102, 0, 153));
        Titlos.setText("Πίνακας Προγραμμάτων");
        getContentPane().add(Titlos);
        Titlos.setBounds(290, 120, 220, 22);

        Shma.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(153, 0, 0), null));
        Shma.setToolTipText("");

        Shma1.setFont(new java.awt.Font("Verdana", 0, 36)); // NOI18N
        Shma1.setForeground(new java.awt.Color(102, 0, 153));
        Shma1.setText("Tele-Pass");
        Shma1.setBounds(290, 20, 180, 40);
        Shma.add(Shma1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        Image.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/toll_image1.jpg"))); // NOI18N
        Image.setToolTipText("");
        Image.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        Image.setBounds(0, 0, 180, 100);
        Shma.add(Image, javax.swing.JLayeredPane.DEFAULT_LAYER);

        Shma2.setFont(new java.awt.Font("Lucida Sans", 0, 14)); // NOI18N
        Shma2.setForeground(new java.awt.Color(102, 0, 153));
        Shma2.setText("Automatic Toll Collection System");
        Shma2.setBounds(290, 70, 230, 30);
        Shma.add(Shma2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        Logotupo.setFont(new java.awt.Font("Bradley Hand ITC", 0, 10)); // NOI18N
        Logotupo.setForeground(new java.awt.Color(102, 0, 153));
        Logotupo.setText("Developed by ANDIMAGI workgroup");
        Logotupo.setBounds(620, 0, 180, 20);
        Shma.add(Logotupo, javax.swing.JLayeredPane.DEFAULT_LAYER);

        getContentPane().add(Shma);
        Shma.setBounds(0, 0, 790, 100);

        Plaisio.setBackground(new java.awt.Color(255, 102, 102));

        NeoProgramma__.setFont(new java.awt.Font("Lucida Sans", 0, 12)); // NOI18N
        NeoProgramma__.setForeground(new java.awt.Color(102, 0, 153));
        NeoProgramma__.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        NeoProgramma__.setText("ΝΕΟ ΠΡΟΓΡΑΜΜΑ");
        NeoProgramma__.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NeoProgramma__(evt);
            }
        });
        Plaisio.add(NeoProgramma__);

        DiaxeirishProgrammatos.setFont(new java.awt.Font("Lucida Sans", 0, 12)); // NOI18N
        DiaxeirishProgrammatos.setForeground(new java.awt.Color(102, 0, 153));
        DiaxeirishProgrammatos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit1.png"))); // NOI18N
        DiaxeirishProgrammatos.setText("ΔΙΑΧΕΙΡΙΣΗ ΠΡΟΓΡΑΜΜΑΤΟΣ");
        DiaxeirishProgrammatos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DiaxeirishProgrammatos(evt);
            }
        });
        Plaisio.add(DiaxeirishProgrammatos);

        DiagrafhProgrammatos.setFont(new java.awt.Font("Lucida Sans", 0, 12)); // NOI18N
        DiagrafhProgrammatos.setForeground(new java.awt.Color(102, 0, 153));
        DiagrafhProgrammatos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        DiagrafhProgrammatos.setText("ΔΙΑΓΡΑΦΗ ΠΡΟΓΡΑΜΜΑΤΟΣ");
        DiagrafhProgrammatos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DiagrafhProgrammatosActionPerformed(evt);
            }
        });
        Plaisio.add(DiagrafhProgrammatos);

        Apo8hkeysh.setFont(new java.awt.Font("Lucida Sans", 0, 12)); // NOI18N
        Apo8hkeysh.setForeground(new java.awt.Color(102, 0, 153));
        Apo8hkeysh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        Apo8hkeysh.setText("ΑΠΟΘΗΚΕΥΣΗ");
        Apo8hkeysh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Apo8hkeush(evt);
            }
        });
        Plaisio.add(Apo8hkeysh);

        getContentPane().add(Plaisio);
        Plaisio.setBounds(560, 170, 220, 230);

        Plaisio1.setBackground(new java.awt.Color(255, 102, 102));
        Plaisio1.setForeground(new java.awt.Color(255, 102, 102));

        Akyro.setFont(new java.awt.Font("Lucida Sans", 0, 12)); // NOI18N
        Akyro.setForeground(new java.awt.Color(102, 0, 153));
        Akyro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        Akyro.setText("ΑΚΥΡΟ");
        Akyro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Akyro(evt);
            }
        });
        Plaisio1.add(Akyro);

        getContentPane().add(Plaisio1);
        Plaisio1.setBounds(560, 400, 220, 50);

        DiaxwristikhGrammh.setForeground(new java.awt.Color(102, 0, 153));
        getContentPane().add(DiaxwristikhGrammh);
        DiaxwristikhGrammh.setBounds(10, 160, 770, 10);

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void NeoProgramma__(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NeoProgramma__
        // TODO add your handling code here:
       p = new Program();
       em.persist(p);
       List<ProgramRate> prl = p.getProgramRateList();
       if (prl==null){
           prl = new ArrayList<ProgramRate>();
           p.setProgramRateList(prl);
       }
       for (Station s: list2){
           for (VehicleCategory vc: list3){
               ProgramRate pr = new ProgramRate();
               pr.setCategoryId(vc);
               pr.setStationId(s);
               pr.setProgramId(p);
               em.persist(pr);
               p.getProgramRateList().add(pr);
           }
       }
     // em.getTransaction().commit();
      
       EditProgramForm epf = new EditProgramForm(p,false);
       
       epf.setVisible(true);
       thisFrame=this;
       thisFrame.setEnabled(false);
       //************
        epf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
               if (((MyWindowEvent)arg0).exitAndSave){
                    
                    
                    list1.add(p);
                    int row = list1.size() - 1;
        
                    Pinakas.setRowSelectionInterval(row, row);
                    Pinakas.scrollRectToVisible(Pinakas.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);
                }
                else{
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = query1.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);
                    }
                    list1.clear();
                    list1.addAll(data);
                }
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
       

    }//GEN-LAST:event_NeoProgramma__

    private void DiagrafhProgrammatosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DiagrafhProgrammatosActionPerformed
        // TODO add your handling code here:
        int s=Pinakas.getSelectedRow();
        if (s>=0) {
            Program p = list1.get(Pinakas.convertRowIndexToModel(s));
            list1.remove(p);
            em.remove(p);
        }
    }//GEN-LAST:event_DiagrafhProgrammatosActionPerformed

    private void DiaxeirishProgrammatos(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DiaxeirishProgrammatos
        // TODO add your handling code here:
       s= Pinakas.getSelectedRow();
       p = list1.get(s);
       EditProgramForm ecf = new EditProgramForm(p,true);
       
       ecf.setVisible(true);
       thisFrame=this;
       thisFrame.setEnabled(false);
       //************
        ecf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                if (((MyWindowEvent)arg0).exitAndSave){
                    
                //    em.merge(p);
                    list1.set(s,p);
                    Pinakas.setRowSelectionInterval(s, s);
                    Pinakas.scrollRectToVisible(Pinakas.getCellRect(s, 0, true));
                    thisFrame.setEnabled(true);
                }
                else{
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = query1.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);
                    }
                    list1.clear();
                    list1.addAll(data);
                }
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
    }//GEN-LAST:event_DiaxeirishProgrammatos

    private void Pinakas(java.awt.event.ContainerEvent evt) {//GEN-FIRST:event_Pinakas
        // TODO add your handling code here:
    }//GEN-LAST:event_Pinakas

    private void Apo8hkeush(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Apo8hkeush
        // TODO add your handling code here:
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED,true);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
        this.setVisible(false);
    }//GEN-LAST:event_Apo8hkeush

    private void Akyro(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Akyro
        // TODO add your handling code here:
        em.getTransaction().rollback();
        em.getTransaction().begin();
        dispose();
    }//GEN-LAST:event_Akyro

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ListProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ListProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ListProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ListProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ListProgramForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Akyro;
    private javax.swing.JButton Apo8hkeysh;
    private javax.swing.JButton DiagrafhProgrammatos;
    private javax.swing.JButton DiaxeirishProgrammatos;
    private javax.swing.JSeparator DiaxwristikhGrammh;
    private javax.swing.JLabel Image;
    private javax.swing.JLabel Logotupo;
    private javax.swing.JButton NeoProgramma__;
    private javax.swing.JTable Pinakas;
    private javax.swing.JScrollPane Pinakas_;
    private javax.swing.JPanel Plaisio;
    private javax.swing.JPanel Plaisio1;
    private javax.swing.JLayeredPane Shma;
    private javax.swing.JLabel Shma1;
    private javax.swing.JLabel Shma2;
    private javax.persistence.EntityManager TelePassPUEntityManager0;
    private javax.swing.JLabel Titlos;
    private java.util.List<model.Program> programList;
    private javax.persistence.Query programQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    EntityManager em;
    JFrame thisFrame;
    Program p;
    int s ;
}
